"use client"

import { useState, useEffect } from "react"
import { useParams } from "react-router-dom"
import "./User.css"
import { fetchUserInfoByIdService } from "../api/UserApi"
import { listUserPostsService, createReportService } from "../api/CommunityApi"

function UserView() {
  const { id } = useParams()
  const [activeTab, setActiveTab] = useState("info")
  const [userInfo, setUserInfo] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [threads, setThreads] = useState([])

  // 举报相关状态
  const [showReportModal, setShowReportModal] = useState(false)
  const [reportReason, setReportReason] = useState("")
  const [isReporting, setIsReporting] = useState(false)

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        setError(null)

        const UserResponse = await fetchUserInfoByIdService(id)
        if (UserResponse.success) {
          setUserInfo(UserResponse.data)
        } else {
          console.error("获取用户信息失败:", UserResponse.message)
          setError(UserResponse.message || "获取用户信息失败")
          return
        }

        const response = await listUserPostsService(id, 1, 200)
        if (response.success) {
          setThreads(response.data.postList || [])
        } else {
          console.error("获取帖子列表失败:", response.message)
        }
      } catch (err) {
        setError(err.message)
        console.error("Failed to load user data", err)
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  // 举报相关函数
  const handleReportUser = () => {
    setReportReason("")
    setShowReportModal(true)
  }

  const handleCloseReportModal = () => {
    setShowReportModal(false)
    setReportReason("")
  }

  const handleSubmitReport = async () => {
    if (!reportReason.trim()) {
      alert("请输入举报原因")
      return
    }

    if (reportReason.trim().length < 5) {
      alert("举报原因至少需要5个字符")
      return
    }

    setIsReporting(true)
    try {
      // 构建举报数据
      const reportData = {
        reportedId: userInfo.id,
        reportedType: "user",
        reason: reportReason.trim(),
      }

      const response = await createReportService(reportData)
      if (!response.success) {
        throw new Error(response.message || "举报提交失败")
      }

      alert("举报提交成功，管理员会尽快处理")
      handleCloseReportModal()
    } catch (err) {
      alert("举报提交失败，请重试")
    } finally {
      setIsReporting(false)
    }
  }

  if (loading) {
    return (
      <div className="loading-container">
        <div className="loading-spinner"></div>
        <p>数据加载中...</p>
      </div>
    )
  }

  if (error) {
    return (
      <div className="error-container">
        <div className="error-icon">⚠️</div>
        <h3>加载失败</h3>
        <p>错误: {error}</p>
        <button className="retry-btn" onClick={() => window.location.reload()}>
          重试
        </button>
      </div>
    )
  }

  const seeds = [
    { id: 1, title: "奥本海默", category: "电影" },
    { id: 2, title: "时间简史", category: "电子书" },
  ]

  const renderContent = () => {
    switch (activeTab) {
      case "info":
        return (
          <div className="content-card">
            <div className="card-header">
              <h2>👤 用户信息</h2>
              <button className="btn btn-report" onClick={handleReportUser}>
                <span className="btn-icon">🚩</span>
                举报用户
              </button>
            </div>
            <div className="card-body">
              <div className="info-grid">
                <div className="info-item">
                  <div className="info-label">用户名</div>
                  <div className="info-value">{userInfo.username}</div>
                </div>
                <div className="info-item">
                  <div className="info-label">邮箱</div>
                  <div className="info-value">{userInfo.email}</div>
                </div>
                <div className="info-item">
                  <div className="info-label">等级</div>
                  <div className="info-value highlight">{userInfo.permissionGroupName}</div>
                </div>
              </div>
            </div>
          </div>
        )

      case "seeds":
        return (
          <div className="content-card">
            <div className="card-header">
              <h2>🌱 种子列表</h2>
            </div>
            <div className="card-body">
              {seeds.length === 0 ? (
                <div className="empty-state">
                  <div className="empty-icon">📦</div>
                  <p>暂无种子数据</p>
                </div>
              ) : (
                <div className="list-container">
                  {seeds.map((seed, id) => (
                    <div key={id} className="list-item">
                      <div className="item-category">{seed.category}</div>
                      <div className="item-title">{seed.title}</div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )

      case "posts":
        return (
          <div className="content-card">
            <div className="card-header">
              <h2>📝 帖子列表</h2>
            </div>
            <div className="card-body">
              {threads.length === 0 ? (
                <div className="empty-state">
                  <div className="empty-icon">📄</div>
                  <p>暂无帖子数据</p>
                </div>
              ) : (
                <div className="list-container">
                  {threads.map((thread, id) => (
                    <div key={id} className="list-item">
                      <div className="item-category">{thread.category}</div>
                      <div className="item-title">{thread.title}</div>
                      <div className="item-meta">
                        点赞: {thread.likeCount} | 回复: {thread.commentCount} | 浏览: {thread.viewCount}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )

      default:
        return null
    }
  }

  return (
    <div className="user-page">
      <div className="sidebar">
        <div className="sidebar-header">
          <div className="user-avatar">
            <img src={userInfo?.avatar_url || "/placeholder.svg?height=50&width=50"} alt="Avatar" />
          </div>
          <h3 className="username">{userInfo?.username}</h3>
          <div className="user-level">{userInfo?.permissionGroupName}</div>
        </div>

        <nav className="sidebar-nav">
          <ul>
            <li onClick={() => setActiveTab("info")} className={activeTab === "info" ? "active" : ""}>
              <span className="nav-icon">👤</span>
              用户信息
            </li>
            <li onClick={() => setActiveTab("seeds")} className={activeTab === "seeds" ? "active" : ""}>
              <span className="nav-icon">🌱</span>
              种子列表
            </li>
            <li onClick={() => setActiveTab("posts")} className={activeTab === "posts" ? "active" : ""}>
              <span className="nav-icon">📝</span>
              帖子列表
            </li>
          </ul>
        </nav>
      </div>

      <div className="main-content">
        <div className="content-wrapper">{renderContent()}</div>
      </div>

      {/* 举报用户弹窗 */}
      {showReportModal && (
        <div className="report-modal-overlay" onClick={handleCloseReportModal}>
          <div className="report-modal-content" onClick={(e) => e.stopPropagation()}>
            <div className="report-modal-header">
              <h3 className="report-modal-title">
                <span className="report-icon">🚩</span>
                举报用户
              </h3>
              <button className="report-modal-close" onClick={handleCloseReportModal}>
                ✕
              </button>
            </div>

            <div className="report-modal-body">
              {/* 举报对象信息 */}
              <div className="report-target-info">
                <h4 className="report-section-title">举报用户</h4>
                <div className="report-target-card">
                  <div className="report-target-meta">
                    <span className="report-target-author">用户名：{userInfo?.username}</span>
                    <span className="report-target-type">用户</span>
                  </div>
                  <div className="report-target-content">
                    <div className="report-target-preview">
                      用户等级：{userInfo?.permissionGroupName}
                      <br />
                      用户ID：{userInfo?.id}
                    </div>
                  </div>
                </div>
              </div>

              {/* 举报原因输入 */}
              <div className="report-reason-section">
                <h4 className="report-section-title">举报原因</h4>
                <div className="report-reason-input-container">
                  <textarea
                    className="report-reason-input"
                    placeholder="请详细说明举报原因，如：恶意行为、违规内容、骚扰他人、虚假信息等..."
                    value={reportReason}
                    onChange={(e) => setReportReason(e.target.value)}
                    rows={4}
                    maxLength={500}
                  />
                  <div className="report-reason-char-count">
                    {reportReason.length}/500
                    {reportReason.length < 5 && reportReason.length > 0 && (
                      <span className="char-count-warning"> (至少5个字符)</span>
                    )}
                  </div>
                </div>

                {/* 常用举报原因提示 */}
                <div className="report-reason-tips">
                  <span className="tips-title">常见举报原因：</span>
                  <div className="tips-tags">
                    {[
                      "恶意行为",
                      "违规内容",
                      "骚扰他人",
                      "虚假信息",
                      "垃圾账号",
                      "不当言论",
                      "侵犯他人",
                      "其他违规",
                    ].map((tip) => (
                      <button key={tip} type="button" className="tip-tag" onClick={() => setReportReason(tip)}>
                        {tip}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className="report-modal-footer">
              <button className="report-cancel-btn" onClick={handleCloseReportModal}>
                取消
              </button>
              <button
                className={`report-submit-btn ${isReporting ? "loading" : ""}`}
                onClick={handleSubmitReport}
                disabled={isReporting || !reportReason.trim() || reportReason.trim().length < 5}
              >
                {isReporting ? (
                  <>
                    <span className="btn-spinner"></span>
                    提交中...
                  </>
                ) : (
                  <>
                    <span className="report-submit-icon">🚩</span>
                    确认举报
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default UserView
